package com.hdl.server.processor;

import com.hdl.request.Request;
import com.hdl.response.Response;
import com.hdl.server.context.Context;
import com.hdl.server.host.Host;
import com.hdl.servlet.HttpServlet;

import java.io.IOException;
import java.io.InputStream;
import java.net.ContentHandler;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 类名 RequestProcessor
 * 描述 请求处理器
 *
 * @author hedonglin
 * @version 1.0
 * @date 2020/5/31 16:54
 */
public class RequestProcessor implements Runnable {
    private Socket socket;
    private List<Host> hosts;

    public RequestProcessor(Socket socket, List<Host> hosts) {
        this.socket = socket;
        this.hosts = hosts;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());


            // 获取host
            Host host = getHost(request);
            Context context = getContext(request, host);

            // 静态资源处理
            Map<String, HttpServlet> servletMap = context.getServletMap();
            final String url = request.getUrl();
            final String path = context.getPath();
            String contextPath = url.substring(path.length());
            if (servletMap.get(contextPath) == null) {
                // 在ROOT里面再找一次
                if (path.equalsIgnoreCase("/")) {
                    // 动态资源servlet请求
                    HttpServlet httpServlet = servletMap.get(url);
                    httpServlet.service(request, response);
                    socket.close();
                    return;
                }
                response.outputHtml(context.getPath() + "/" + request.getUrl());
            } else {
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(contextPath);
                httpServlet.service(request, response);
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Host getHost(Request request) {
        return this.hosts.get(0);
    }

    private Context getContext(Request request, Host host) {
        String url = request.getUrl();
        if (url.equalsIgnoreCase("/")) {
            // 跳转到ROOT
        } else {
            List<Context> context = host.getContext();
            for (Context c : context) {
                if (url.startsWith(c.getPath())) {
                    // 获取到对应的Context
                    return c;
                }
            }
        }
        return null;
    }
}
